<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/1/27
 * Time: 18:01
 */
declare(strict_types=1);
namespace App\Service;
use App\Constants\XZXResponseCode;
use App\Exception\XZXValidationException;
use App\Model\Dao\EmailCheckDao;
use App\Model\Dao\MchConfigDao;
use App\Model\Dao\MchInfoDao;
use App\Utils\CustomUtils;
use App\Utils\NumberUtils;
use App\Utils\RedisUtils;
use Hyperf\Di\Annotation\Inject;
use App\Service\EmailService;

class EmailCheckService
{
    /**
     * @Inject()
     * @var EmailService
     */
    private $EmailService;

    /**
     * @Inject()
     * @var EmailCheckDao
     */
    private $EmailCheckDao;

    /**
     * @Inject()
     * @var MchInfoDao
     */
    private $MchInfoDao;

    /**
     * @Inject()
     * @var MchConfigDao
     */
    private $MchConfigDao;

    /**
     * @param $param
     * @return array
     * 发送
     */
    public function add($param) {
        $key = "email::". $param['email'];
        $sendLimit = config('emailSendLimit');
        $isValid = RedisUtils::redisResource()->get($key);
        if ($isValid) {
            throw new XZXValidationException($sendLimit . "s内请勿重复发送验证码");
        }
        RedisUtils::redisResource()->set($key, 1, config('emailSendLimit'));

        $now = time();
        $expireLimit = config('emailCodeExpireLimit');
        $isCode = $this->EmailCheckDao->getByEmailAndType($param['email'], $param['type']);
        if ($isCode && $isCode['expireTime'] > $now) {
            $data['expireTime'] = $now + $expireLimit;
            $this->EmailCheckDao->update($isCode['id'], $data);
            $sendMailParam = array(
                'type'     => $param['type'],
                'regEmail' => $param['email'],
                'code'     => $isCode['code'] 
            );
            $this->EmailService->addMq($sendMailParam);
            return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE, XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE), $isCode['code']);
        }

        $data = [
            'id'            => CustomUtils::createUUID(),
            'email'         => $param['email'],
            'type'          => $param['type'],
            'code'          => NumberUtils::random(6),
            'status'        => 0,
            'createTime'    => $now,
            'expireTime'    => $now + $expireLimit
        ];
        try {
            //code...
            $this->EmailCheckDao->add($data);
            $sendMailParam = array(
                'type'     => $param['type'],
                'regEmail' => $param['email'],
                'code'     => $data['code'] 
            );
            $this->EmailService->addMq($sendMailParam);
        } catch (\Throwable $th) {
            //throw $th;
            throw new XZXValidationException("发送验证码失败");
        }
        

        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE, XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE), $data['code']);
    }

    /**
     * @param $param
     * @return array
     * 验证
     */
    public function check($param) {
        $isCode = $this->EmailCheckDao->getByEmailAndType($param['email'], $param['type']);
        if (empty($isCode)) {
            throw new XZXValidationException("验证码无效");
        }
        $now = time();
        if ($isCode['expireTime'] < $now) {
            throw new XZXValidationException("验证码已过期");
        }
        if ($isCode['code'] != $param['code']) {
            throw new XZXValidationException("验证码不正确");
        }
        $updateData = [
            'status' => 1,
        ];
        $this->EmailCheckDao->update($isCode['id'], $updateData);
        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE, XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE), '');
    }

    /**
     * @param $param
     * 检查email
     * @return array
     */
    public function checkEmailValid($param) {
        $isMch = $this->MchInfoDao->getByEmail($param['email']);
        if (!empty($isMch)) {
            return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE, XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE), 0);
        } else {
            return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE, XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE), 1);
        }
    }

    /**
     * @param $param
     * 检查email
     * @return array
     */
    public function checkEmailValidAndSettleCurrency($param) {
        $isMch = $this->MchInfoDao->getByEmail($param['email']);
        if (empty($isMch) || $isMch['status'] != 1) {
            $data = [
                'isValid' => 0,
            ];
        } else {
            $config = $this->MchConfigDao->getByMchId($isMch['id']);
            if (empty($config)) {
                throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::NOT_SET_MCH_CONFIG));
            }
            $data = [
                'isValid' => 1,
                'settleCurrency' => $config['settleCurrency']
            ];
        }
        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE, XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE), $data);
    }

}